﻿using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Prompts.Service.PromptService;

namespace Prompts.PromptServiceProxy
{
    [ServiceContract(ConfigurationName="Prompts.Prompting.Model.IPromptService")]
    public interface IPromptService
    {
        [OperationContractAttribute(
            AsyncPattern=true, 
            Action="http://tempuri.org/IPromptService/GetPromptsForReport", 
            ReplyAction="http://tempuri.org/IPromptService/GetPromptsForReportResponse")]
        IAsyncResult BeginGetPromptsForReport(string path, AsyncCallback callback, object asyncState);
        
        GetPromptsResponse EndGetPromptsForReport(IAsyncResult asyncResult);
    }
    
    public interface IPromptServiceChannel : IPromptService, IClientChannel
    {
    }
    
    
    public class PromptServiceClient : ClientBase<IPromptService>, IPromptServiceClient
    {
        public PromptServiceClient(Binding binding, EndpointAddress remoteAddress) : 
                base(binding, remoteAddress)
        {
        }
        
        public void GetPromptsForReportAsync(string path, Action<GetPromptsResponse> callBack)
        {

            InvokeAsync(
                (inValues, callback, asyncState) =>
                    {
                        var path1 = (string)inValues[0];
                        return Channel.BeginGetPromptsForReport(path1, callback, asyncState);
                    }, 
                new object[] {path}, 
                result =>
                    {
                        try
                        {
                            var retVal = Channel.EndGetPromptsForReport(result);
                            return new object[] { retVal };
                        }
                        catch (Exception exception)
                        {
                            var response = new GetPromptsResponse
                                {
                                    ErrorOccured = true, 
                                    ErrorMessage = exception.Message
                                };
                            return new object[]{response};
                        }

                    }, 
                state =>
                    {
                        var e = (InvokeAsyncCompletedEventArgs)state;
                        callBack((GetPromptsResponse)e.Results[0]);
                    }, 
                new object());
        }
    }
}
